<?php
	include '../common/db.inc';	
	include '../common/paging.php';
	$conn = new mysqli($host, $username, $password, $dbname);	
	$conn->query("set names 'utf8'");
	
	$field = $conn->real_escape_string($_GET['field']);
	$category = $conn->real_escape_string($_GET['category']);
	$orderby = "";
	$sort = "";
	if(isset($_GET['orderby']))
		$orderby = $conn->real_escape_string($_GET['orderby']);
	else
		$orderby = "Title";
	if(isset($_GET['sort']))
		$sort = $conn->real_escape_string($_GET['sort']);
	else
		$sort = "asc";
		
	$pagesize = 12;
	$currentpage = 1;
	$numdisplay = 5;
	
	if (isset($_GET["page"]))
		$currentpage = $conn->real_escape_string($_GET["page"]);
	$start = ($currentpage-1) * $pagesize;

	$query = "call sp_GetEbookByCategory($category, '$orderby', '$sort', $start, $pagesize)";
	if($listbook = @$conn->query($query))
	{
		$count =  mysqli_num_rows($listbook);
		echo "<table width='100%' cellspacing='6' class='showbook'>";	
		$i = 0;
		$user = $_SESSION['user_id'];
		while($book = $listbook->fetch_row())
		{
			$ebookId = $book[0];
			$title = $book[1];
			$author = $book[5];
			$img = $image.$book[8];	
			$mana = $book[13];
			
			if($i%4 == 0)
				echo "<tr>";
			echo "<td valign='top' width='25%'><a href='XemChiTietSach.php?id=$book[0]'><img src='$img' width='100px' height='150px' alt='EBook'/></a><br/>";
			echo "<a href='XemChiTietSach.php?id=$book[0]'><b>$title</b></a><br/>";
			echo "<label><i>Tác giả: </i>$author</label><br/>";
			echo "<label><i>Mana: </i>$mana</label><br/>";
			echo "<a href='XemChiTietSach.php?id=$book[0]'>Xem chi tiết</a><br/>";
			if($_SESSION['user_mana'] >= $mana)
				echo "<input type='button' value='Tải về' onClick='download(\"$user\", \"$ebookId\", \"$book[2]\")'></input>";
			else
				echo "<input type='button' disabled='disabled' value='Tải về'></input>";
			echo "</td>";
			if($i % 4 == 3 || $i == $count-1)
				echo "</tr>";
			$i++;
		}
		echo "</table>";
		
		$count = 0;
		$conn = new mysqli($host, $username, $password, $dbname);
		$query = "call sp_CountGetEbookByCategory($category)";
		$result = @$conn->query($query);
		$row = $result->fetch_row();
		$count = $row[0];
		$conn->close();
		
		echo paging('showbook.php', $pagesize, $numdisplay, $count, $currentpage, '&field='.$field.'&category='.$category.'&orderby='.$orderby.'&sort='.$sort);
		
	}
	
?>
